﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using BUS;
using DAO;
using System.Windows.Forms;
using System.IO;
using Control = System.Web.UI.Control;

public partial class Admin_Pages_WRUSER : BasePage
{
    public static bool Insert;
    BUS_WRUSER busUser = new BUS_WRUSER();
    BUS_WRCITIZEN busCitizen = new BUS_WRCITIZEN();
    BUS_WRUSERGROUP busUserGroup = new BUS_WRUSERGROUP();
    BUS_WRLANGUAGE busWrlanguage = new BUS_WRLANGUAGE();

    DataTable _dtUser = new DataTable();
    Encrypt en = new Encrypt();
    protected void Page_Load(object sender, EventArgs e)
    {
        Page.MaintainScrollPositionOnPostBack = true;
        if (!IsPostBack)
        {
            pnUpdate.Visible = false;
            pnShow.Visible = true;
            BindGrid();
            BindDropDownList();
        }
    }
    private void BindGrid()
    {
        grvUser.DataSource = busUser.Get_User_List();
        grvUser.DataBind();
    }

    private void BindDropDownList()
    {
        ddlCitizen.DataSource = busCitizen._GetList().Where(q=>q.Active == "Y").Select(p => new { p.ID, p.CountryName }).ToList();
        ddlCitizen.DataTextField = "CountryName";
        ddlCitizen.DataValueField = "ID";
        ddlCitizen.DataBind();
        string lang = Request.Cookies["SelLang"].Value;
        if (lang == "vi")
        {
                ddlUserGroup.DataSource =
                    busUserGroup._GetList()
                        .Where(q => q.Active == "Y" && q.IDLang == 2)
                        .Select(p => new {p.ID, p.UserGroupName})
                        .ToList();
                ddlUserGroup.DataTextField = "UserGroupName";
                ddlUserGroup.DataValueField = "ID";
                ddlUserGroup.DataBind();
        }
        else
        {
            ddlUserGroup.DataSource = busUserGroup._GetList().Where(q => q.Active == "Y" && q.IDLang == 1).Select(p => new { p.ID, p.UserGroupName }).ToList();
            ddlUserGroup.DataTextField = "UserGroupName";
            ddlUserGroup.DataValueField = "ID";
            ddlUserGroup.DataBind();
        }
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        pnUpdate.Visible = true;
        pnShow.Visible = false;
        Insert = true;
        txtUsername.Text = "";
        txtPassword.Text = "";
        txtBirthday.Text = DateTime.Now.Date.ToShortDateString();
        txtPassword.Enabled = true;
        txtFirstname.Text = "";
        txtLastname.Text = "";
        Session["upload"] = "";
        txtEmail.Text = "";
        txtAddress.Text = "";
        txtPhone.Text = "";
        txtRsPssQuestion.Text = "";
        txtRsPssAnswer.Text = "";
        ddlCitizen.SelectedIndex = -1;
        ddlUserGroup.SelectedIndex = -1;
        txtDescription.Text = "";
        txtIP.Text = "";
        ddlActive.SelectedIndex = -1;
        BindDropDownList();
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        if (grvUser.Items.Count > 0)
        {
            for (int i = 0; i < grvUser.Items.Count; i++)
            {
                System.Web.UI.WebControls.CheckBox chkSelect = (System.Web.UI.WebControls.CheckBox)grvUser.Items[i].FindControl("chkSelect");
                if (chkSelect.Checked)
                {
                    string Id = grvUser.Items[i].Cells[1].Text;
                    try
                    {
                        busUser._Delete(Convert.ToInt32(Id));
                    }
                    catch
                    {
                    }
                }
            }
            BindGrid();
        }
    }
    private void Show(string Mess)
    {
        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('" + Mess + "')", true);
    }
    protected void grvUser_ItemCommand(object source, DataGridCommandEventArgs e)
    {
        string Id = e.CommandArgument.ToString();
        if (e.CommandName == "Edit")
        {

            Insert = false;
            WRUSER _user = busUser._GetObject(Convert.ToInt32(Id));
            txtID.Text = Id;
            txtUsername.Text = _user.Username;           
            txtPassword.Enabled = false;
            txtUsername.Enabled = false;
            txtFirstname.Text = _user.Firstname;
            txtLastname.Text = _user.Lastname;
            txtBirthday.Text = _user.BirthDay.ToString() == "" ? "" : Convert.ToDateTime(_user.BirthDay.ToString()).ToShortDateString();
            txtEmail.Text = _user.Email;
            txtAddress.Text = _user.Address;
            txtPhone.Text = _user.Phone;
            Session["upload"] = _user.Avatar;
            txtRsPssQuestion.Text = _user.RsPssQuestion;
            txtRsPssAnswer.Text = _user.RsPssAnswer;
            try
            {
                ddlCitizen.SelectedValue = _user.IDCitizen.ToString();
            }
            catch
            {
                Show("Citizen is not active!");
            }
            try
            {
                ddlUserGroup.SelectedValue = _user.IDUserGroup.ToString();
            }
            catch
            {
                Show("UserGroup is not active!");
            }
            txtDescription.Text = _user.Description;
            txtIP.Text = _user.IP;
            ddlActive.SelectedIndex = _user.Active == "Y" ? 0 : 1;
            pnUpdate.Visible = true;
            pnShow.Visible = false;
        }
        else if (e.CommandName == "Delete")
        {
            busUser._Delete(Convert.ToInt32(Id));
            BindGrid();
        }
    }
    protected void grvUser_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
    {
        grvUser.CurrentPageIndex = e.NewPageIndex;
        BindGrid();
    }
    protected void btnOk_Click(object sender, EventArgs e)
    {
        if (txtUsername.Text.Trim().Equals(""))
        {
            Show("Bạn chưa nhập Username!");
            txtUsername.Focus();
            return;
        }
        if (txtFirstname.Text.Trim().Equals(""))
        {
            Show("Bạn chưa nhập FirstName!");
            txtUsername.Focus();
            return;
        }
        if (txtLastname.Text.Trim().Equals(""))
        {
            Show("Bạn chưa nhập LastName!");
            txtUsername.Focus();
            return;
        }
        if (Insert ==true)
        {
            if (txtPassword.Text.Trim().Equals(""))
            {
                Show("Bạn chưa nhập Password!");
                txtPassword.Focus();
                return;
            }
        }
        if (ddlCitizen.Text.Trim().Equals(""))
        {
            Show("Bạn chưa chọn Citizen!");
            ddlCitizen.Focus();
            return;
        }
        if (ddlUserGroup.Text.Trim().Equals(""))
        {
            Show("Bạn chưa chọn UserGroup!");
            ddlUserGroup.Focus();
            return;
        }
        if (ddlActive.Text.Trim().Equals(""))
        {
            Show("Bạn chưa chọn Active!");
            ddlUserGroup.Focus();
            return;
        }
        WRUSER obj = new WRUSER();
        obj.Username = txtUsername.Text;        
        obj.Firstname = txtFirstname.Text;
        obj.Lastname = txtLastname.Text;
        obj.BirthDay = Common.Common.ConvertDateTime(txtBirthday.Text) == "" ? (DateTime?)null : Convert.ToDateTime(txtBirthday.Text);
        obj.Email = txtEmail.Text;
        obj.Address = txtAddress.Text;
        obj.Phone = txtPhone.Text;
        obj.RsPssQuestion = txtRsPssQuestion.Text;
        obj.RsPssAnswer = txtRsPssAnswer.Text;
        obj.IDCitizen = Convert.ToInt32(ddlCitizen.SelectedValue);
        obj.IDUserGroup = Convert.ToInt32(ddlUserGroup.SelectedValue);
        obj.UpdateDate = DateTime.Now;
        obj.IDUpdateBy = Convert.ToInt32(Session["userid"].ToString());
        obj.Description = txtDescription.Text;
        obj.IP = txtIP.Text;
        obj.Active = ddlActive.Text;
        if (Insert)
        {
            txtPassword.CausesValidation = true;
            obj.Password = en.Mahoa(txtPassword.Text);
            obj.Avatar = Session["upload"].ToString() == "" ? "~/Images/Pic/no-image.png" : Session["upload"].ToString();
            obj.CreateDate = DateTime.Now;
            busUser._Add(obj);
            
        }
        else
        {
            txtPassword.CausesValidation = false;
            obj.ID = Convert.ToInt32(txtID.Text);
            obj.Avatar = Session["upload"].ToString() == "" ? "~/Images/Pic/no-image.png" : Session["upload"].ToString();
            busUser._Update(obj);
        }
        BindGrid();
        pnUpdate.Visible = false;
        pnShow.Visible = true;
        Insert = false;
    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        pnUpdate.Visible = false;
        pnShow.Visible = true;
    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        HttpPostedFile files = FileUpload1.PostedFile;
        if (FileUpload1.HasFile == false || files.ContentLength > 500000)
        {
            Show("Ảnh không hợp lệ!");
        }
        else
        {
            string _fileExt = Path.GetExtension(FileUpload1.FileName);
            if (_fileExt.ToLower() == ".gif" || _fileExt.ToLower() == ".png" || _fileExt.ToLower() == ".bmp" ||
                _fileExt.ToLower() == ".jpeg" || _fileExt.ToLower() == ".jpg")
            {
                try
                {
                    string filePath = "~/Images/Pic/" + DateTime.Now.Ticks.ToString() + "_" + Session["userid"].ToString() + _fileExt;
                    FileUpload1.SaveAs(Server.MapPath(filePath));
                    Session["upload"] = "~/Images/Pic/" + DateTime.Now.Ticks.ToString() + "_" + Session["userid"].ToString() + _fileExt;
                    Show("Tải thành công!");
                }
                catch
                {
                    Show("Trùng tên hoặc chưa chọn hình!");
                }
            }
            else
            {
                Show("Không đúng định dạng ảnh!");
            }
        }
    }
    protected void ibtCal_Click(object sender, ImageClickEventArgs e)
    {

    }
}